import BreadcrumbDept from '@/components/BreadcrumbDept';
import PermissionControl from '@/components/PermissionControl/index';
import { addLevelInfo, deleteLevelInfo, editLevelInfo, getLevelList } from "@/services/patient/levelApi";
import { isExits, showMsg } from "@/utils/utils";
import { PageContainer } from "@ant-design/pro-layout";
import { EditableProTable, ProColumns } from "@ant-design/pro-table";
import { Card, Form, Popconfirm } from "antd";
import { useState } from "react";

const Level = () => {

  const [editFormRef] = Form.useForm();
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);
  const [dataSource, setDataSource] = useState<any[]>([]);
  const [loading, setLoading] = useState<boolean>(false);

  const columns: ProColumns<any>[] = [
    {
      title: '等级',
      dataIndex: 'rank',
      valueType: 'digit',
      fieldProps: { style: { width: '100%' } },
      formItemProps: { rules: [{ required: true, message: '等级是必填项' }] }
    },
    {
      title: '累计积分',
      dataIndex: 'integral',
      valueType: 'digit',
      fieldProps: { style: { width: '100%' } },
      formItemProps: { rules: [{ required: true, message: '累计积分是必填项' }] }
    },
    {
      title: '订单折扣',
      dataIndex: 'discount',
      valueType: 'digit',
      fieldProps: { style: { width: '100%' } },
      formItemProps: { rules: [{ required: true, message: '订单折扣是必填项' }] }
    },
    {
      title: '操作',
      valueType: 'option',
      align: 'center',
      width: '15%',
      render: (_, record, idx, action) => [
        <PermissionControl key="edit" action_id="900901017">
          <a onClick={() => action?.startEditable?.(record.key)}>编辑</a>
        </PermissionControl>,
        <PermissionControl key="del" action_id="900901018">
          <Popconfirm placement="topRight" title='确认删除？' onConfirm={async () => {
            try {
              setLoading(true);
              await deleteLevelInfo(record.rank_id);
              action?.reload();
            } catch (error: any) {
              showMsg(error?.data?.errmsg);
            } finally {
              setLoading(false);
            }
          }}>
            <a>删除</a>
          </Popconfirm>
        </PermissionControl>
      ]
    }
  ];

  return (
    <PageContainer extra={<BreadcrumbDept />} breadcrumb={{}}>
      <Card bodyStyle={{ padding: '6px 12px 12px' }}>
        <EditableProTable
          rowKey="key"
          columns={columns}
          loading={loading}
          bordered
          maxLength={101}
          cardProps={{ bodyStyle: { padding: 0 } }}
          recordCreatorProps={
            isExits('900901016')
              ? { creatorButtonText: '添加一个等级', newRecordType: "dataSource", record: () => ({ key: Date.now() }) }
              : false
          }
          request={async params => {
            setLoading(true);
            try {
              const res = await getLevelList({ current: 1, pageSize: 99 });
              res.record_list.forEach(elem => elem['key'] = elem.rank_id);
              return { success: true, data: res.record_list, total: res.sum_record_num };
            } catch (error: any) {
              showMsg(error?.data?.errmsg);
              return { success: false, data: [] };
            } finally {
              setLoading(false);
            }
          }}
          value={dataSource}
          onChange={setDataSource}
          editable={{
            form: editFormRef,
            type: 'single',
            editableKeys,
            onChange: setEditableRowKeys,
            onlyOneLineEditorAlertMessage: '请先保存之前编辑的等级信息',
            onlyAddOneLineAlertMessage: '请先保存之前新增的等级信息',
            actionRender: ({ rank_id, key, index }) => {
              const newDS = [...dataSource];
              return [
                <a key="save" onClick={() => {
                  editFormRef.validateFields().then(async values => {
                    const data = { ...values[key] };
                    try {
                      setLoading(true);
                      if (rank_id) {
                        await editLevelInfo({ ...data, rank_id });
                        showMsg('修改成功', 'success');
                      } else {
                        const res = await addLevelInfo(data);
                        data.rank_id = res.rank_id;
                        showMsg('添加成功', 'success');
                      }
                      newDS[index] = data;
                      setDataSource(newDS);
                      setEditableRowKeys([]);
                    } catch (error: any) {
                      showMsg(error?.data?.errmsg);
                    } finally {
                      setLoading(false);
                    }
                  }).catch(error => { });
                }}>保存</a>
                ,
                <a key="cancel" onClick={() => {
                  setDataSource(dataSource.filter(r => r.key !== key));
                  setEditableRowKeys([]);
                }}>取消</a>
              ];
            }
          }}
        />
      </Card>
    </PageContainer>
  );
};

export default Level;
